import 'dart:developer' as developer;
import 'package:azring/common/langs/index.dart';
import 'package:azring/common/styles/theme.dart';
import 'package:azring/pages/login/page/login_view.dart';
import 'package:azring/pages/sleep/sleep_logic.dart';
import 'package:azring/pages/status/status_logic.dart';
import 'package:azring/routes/index.dart';
import 'package:azring/services/ring_service.dart';
import 'package:azring/services/device_storage_service.dart';
import 'package:azring/services/device_sn_manager.dart';
import 'package:azring/core/controllers/ring_controller.dart';
import 'package:azring/core/services/storage_service.dart';
import 'package:azring/pages/status/status_page.dart';
import 'package:azring/pages/login/login_router.dart';
import 'package:azring/core/controllers/auth_controller.dart';
import 'package:azring/pages/action/actionLogic.dart';
import 'package:azring/pages/insights/InsightsLogic.dart';
import 'package:azring/pages/profile/ProfileLogic.dart';
import 'package:azring/pages/status/daily_events/daily_events_logic.dart';
import 'package:azring/common/styles/theme_manager.dart';
import 'package:azring/core/controllers/mood_emoji_controller.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:getx_scaffold/getx_scaffold.dart';

/**
 * @author: Kxmrg
 * @github: https://github.com/Kxmrg
 * @version: 1.0.0
 * @copyright: Copyright © 2023-2024 Kxmrg
 * @license: MIT License
 * @date: 2024-07-03
 * @description: 
 */

/// Main
void main() async {
  WidgetsBinding widgetsBinding = await init(
    isDebug: kDebugMode,
    logTag: 'GetxScaffold',
    supportedLocales: TranslationLibrary.supportedLocales,
  );
  // 设置只允许竖屏方向
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
  FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);

  // 初始化存储服务
  await Get.putAsync(() => StorageService().init());

  // 初始化主题管理器
  Get.put<ThemeManager>(ThemeManager(), permanent: true);

  // 获取token并判断是否已登录
  String? token = StorageService.to.getToken();
  final bool isLoggedIn = token?.isNotEmpty == true;

  // 始终初始化AuthController（登录功能需要）
  Get.put<AuthController>(AuthController(), permanent: true);
  developer.log('✅ AuthController 初始化成功', name: 'Main');

  // 先初始化全局依赖（服务、存储等），确保被控制器依赖的服务已注册
  await _initGlobalDependencies();

  // 再初始化核心控制器（依赖已就绪）
  isLoggedIn ? await initCoreControllers() : null;

  runApp(
    GetxApp(
      // 设计稿尺寸 单位：dp
      designSize: const Size(393, 852),
      minTextAdapt: true, // 文本自适应优化
      splitScreenMode: true, // 支持分屏模式
      // Getx Log
      enableLog: kDebugMode,
      // 默认的跳转动画
      defaultTransition: Transition.fadeIn,
      // 主题模式 - 默认深色模式
      themeMode: ThemeMode.dark,
      // 主题
      theme: AppTheme.light,
      // Dark主题
      darkTheme: AppTheme.dark,
      // 国际化配置
      locale: GlobalService.to.locale,
      translations: TranslationLibrary(),
      fallbackLocale: TranslationLibrary.fallbackLocale,
      supportedLocales: TranslationLibrary.supportedLocales,
      localizationsDelegates: TranslationLibrary.localizationsDelegates,
      // AppTitle
      title: 'AZring',
      // 路由配置
      getPages: [...AppPages.routes, ...LoginRouter.routes],
      // 根据登录状态决定首页
      home: isLoggedIn ? const StatusView() : const LoginView(),
      // home: const StatusView(),
      // Builder
      builder: (context, widget) {
        // 移除开屏页
        FlutterNativeSplash.remove();
        return widget!;
      },
    ),
  );
}

/// 初始化核心控制器
Future<void> initCoreControllers() async {
  try {
    // Get.put(VersionController());

    Get.put<RingController>(RingController(), permanent: true);

    Get.put<StatusLogic>(StatusLogic(), permanent: true);

    Get.put<SleepLogic>(SleepLogic(), permanent: true);

    Get.put<ActionLogic>(ActionLogic(), permanent: true);

    Get.put<InsightsLogic>(InsightsLogic(), permanent: true);

    Get.put<ProfileLogic>(ProfileLogic(), permanent: true);

    Get.put<DailyEventsLogic>(DailyEventsLogic(), permanent: true);

    Get.put<MoodEmojiController>(MoodEmojiController(), permanent: true);
    
    developer.log('✅ 核心控制器初始化完成', name: 'Main');
  } catch (e) {
    developer.log('❌ 核心控制器初始化失败: $e', name: 'Main');
  }
}

/// 初始化全局依赖
Future<void> _initGlobalDependencies() async {
  try {
    final storageService = StorageService();
    await storageService.init();
    Get.put<StorageService>(storageService, permanent: true);

    Get.put<DeviceStorageService>(DeviceStorageService(), permanent: true);

    Get.put<DeviceSnManager>(DeviceSnManager(), permanent: true);

    Get.put<RingService>(RingService(), permanent: true);

    // 只在已登录时才尝试自动重连
    await _startAutoReconnectCheck();

    developer.log('✅ 全局依赖初始化完成', name: 'Main');
  } catch (e) {
    developer.log('❌ 全局依赖初始化失败: $e', name: 'Main');
  }
}

/// 启动设备自动重连（仅在已登录时执行）
Future<void> _startAutoReconnectCheck() async {
  try {
    // 检查用户是否已登录
    if (!Get.isRegistered<AuthController>()) {
      return;
    }
    
    final authController = Get.find<AuthController>();
    if (!authController.isLoggedIn) {
      developer.log('⚠️ 用户未登录，跳过自动重连', name: 'Main');
      return;
    }
    
    if (Get.isRegistered<RingService>()) {
      final ringService = Get.find<RingService>();
      await ringService.checkAndAutoReconnect();
    }
  } catch (e) {
    developer.log('❌ 自动重连检查失败: $e', name: 'Main');
  }
}
